<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\controller;
use think\facade\Db;
class ApiForm extends ApiCommon
{	
	//提交表单
	public function formsubmit(){
		$this->checklogin();
		$post = input('post.');
		//var_dump($post);
		//var_dump($post['formdata']);
		//die;
		$form = Db::name('form')->where('aid',aid)->where('id',$post['formid'])->find();
		if(strtotime($form['starttime']) > time()){
			return $this->json(['status'=>0,'msg'=>'活动未开始']);
		}
		if(strtotime($form['endtime']) < time()){
			return $this->json(['status'=>0,'msg'=>'活动已结束']);
		}
		if($form['maxlimit'] > 0){
			$count = 0 + Db::name('form_order')->where('formid',$form['id'])->count();
			if($count >= $form['maxlimit']){
				return $this->json(['status'=>0,'msg'=>'提交人数已满']);
			}
		}
		$mycs = 0 + Db::name('form_order')->where('formid',$form['id'])->where('mid',mid)->count();
		if($form['perlimit'] > 0 && $mycs >= $form['perlimit']){
			return $this->json(['status'=>0,'msg'=>$form['perlimit']==1?'您已经提交过了':'每人最多可提交'.$form['perlimit'].'次']);
		}

        //判断表单是否超出范围
        if($form['fanwei'] == 1){
            if(empty($post['longitude']) || empty($post['latitude'])){
                return $this->json(['status'=>0,'msg'=>'请定位您的位置或者刷新重试']);
            }
            $juli = getdistance($post['longitude'],$post['latitude'],$form['fanwei_lng'],$form['fanwei_lat'],1);
            if($juli > $form['fanwei_range']){
                return $this->json(['status'=>0,'msg'=>'请在指定范围内使用']);
            }
        }
		
		$data =[];
		$data['aid'] = aid;
		$data['bid'] = $form['bid'];
		$data['formid'] = $form['id'];
		$data['title'] = $form['name'];
		$data['mid'] = mid;
		$data['createtime'] = time();

		//var_dump($post);
		$fromdata = $post['formdata'];
		$formcontent = json_decode($form['content'],true);
		foreach($formcontent as $k=>$v){
			$value = $fromdata['form'.$k];
			if(is_array($value)){
				$value = implode(',',$value);
			}
			if($v['key']=='switch'){
				if($value){
					$value = '是';
				}else{
					$value = '否';
				}
			}
			$data['form'.$k] = strval($value);
			if($v['val3']==1 && $data['form'.$k]===''){
				return $this->json(['status'=>0,'msg'=>$v['val1'].' 必填']);
			}
		}
		$price = 0;
		if($form['payset']==1){
		    $is_other_fee = 0;
            if($is_other_fee==0){
                if($form['priceedit']==1){
                    $price = $post['price'];
                }else{
                    $price = $form['price'];
                }
            }
		}
		$ordernum = date('ymdHis').aid.rand(1000,9999);
		$data['money'] = $price;
		$data['ordernum'] = $ordernum;
		$data['fromurl'] = $post['fromurl'];

		if(false){}else{
			$orderid = Db::name('form_order')->insertGetId($data);
		}
		//订阅消息
		$tmplids = [];
		if(platform == 'wx'){
			$wx_tmplset = Db::name('wx_tmplset')->where('aid',aid)->find();
			if($wx_tmplset['tmpl_shenhe_new']){
				$tmplids[] = $wx_tmplset['tmpl_shenhe_new'];
			}elseif($wx_tmplset['tmpl_shenhe']){
				$tmplids[] = $wx_tmplset['tmpl_shenhe'];
			}
		}

		if(!$orderid) return $this->json(['status'=>0,'msg'=>'提交失败','tmplids'=>$tmplids]);
		if($price > 0){
			$payorderid = \app\model\Payorder::createorder(aid,$data['bid'],$data['mid'],'form',$orderid,$data['ordernum'],$data['title'],$data['money']);
			return $this->json(['status'=>2,'msg'=>'需要支付','orderid'=>$orderid,'payorderid'=>$payorderid,'tmplids'=>$tmplids,'is_other'=>$is_other_fee,'fee'=>$feedata]);
		}else{
			$tmplcontent = [];
			$tmplcontent['first'] = '有客户提交表单成功';
			$tmplcontent['remark'] = '点击查看详情~';
			$tmplcontent['keyword1'] = $form['name'];
			$tmplcontent['keyword2'] = date('Y-m-d H:i');
			\app\common\Wechat::sendhttmpl(aid,$form['bid'],'tmpl_formsub',$tmplcontent,m_url('admin/form/formdetail?id='.$orderid));
			return $this->json(['status'=>1,'msg'=>'提交成功','tmplids'=>$tmplids]);
		}
	}

	//查询表单
	public function formquery(){
		$post = input('post.');
		$form = Db::name('form')->where('aid',aid)->where('id',$post['formid'])->find();
		if($form['form_query']!='1') return json(['status'=>0,'msg'=>'该表单未开启查询功能']);
		
		$fromdata = $post['formdata'];
		$formcontent = json_decode($form['content'],true);
		$newformdata = [];
		foreach($formcontent as $fk=>$fv){
			if($fv['query'] == '1'){
				$fv['oldkey'] = $fk;
				$newformdata[] = $fv;
			}
		}
		$formcontent = $newformdata;


		$where = [];
		$where[] = ['aid','=',$form['aid']];
		$where[] = ['formid','=',$form['id']];

		$data = [];
		foreach($formcontent as $k=>$v){
			$value = $fromdata['form'.$k];
			if(is_array($value)){
				$value = implode(',',$value);
			}
			if($v['key']=='switch'){
				if($value){
					$value = '是';
				}else{
					$value = '否';
				}
			}
			$data[] = strval($value);

			$field = 'form'.$v['oldkey'];
			$val = strval($value);
			if($form['form_query_type'] == 0){
				if($val){
					$order = Db::name('form_order')->where('aid',aid)->where('formid',$form['id'])->where($field,$val)->order('id desc')->find();
					if($order) break;
				}
			}else{
				if(!$val){
					return json(['status'=>0,'msg'=>'请输入'.$v['val1']]);
				}
				$where[] = [$field,'=',$val];
			}
		}
		if($form['form_query_type'] == 1){
			$order = Db::name('form_order')->where($where)->order('id desc')->find();
		}
		if(!$order) return json(['status'=>0,'msg'=>'未查询到相关数据']);
		cache($this->sessionid.'_formquery',$order['id'],86400);

		return json(['status'=>1,'msg'=>'查询成功','tourl'=>'/pages/form/formdetail?id='.$order['id'].'&op=view']);
	}

	//获取上一次的数据
	public function getlastformdata(){
		$formid = input('param.formid/d');
		if(!$formid || !$this->member) return json(['status'=>0,'msg'=>'参数错误']);
		$formorder = [];
		if(input('param.fromrecord')){
			$formorder = Db::name('form_order')->where('aid',aid)->where('id',input('param.fromrecord'))->where('mid',mid)->order('id desc')->find();
		}else{
			}
		if(!$formorder){
			return json(['status'=>0,'msg'=>'没有记录']);
		}
		return json(['status'=>1,'data'=>$formorder]);
	}
}